﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using DataGridView.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.ComponentModel;
using System.Windows;
using System.Collections.ObjectModel;
using FreeSql;

namespace DataGridView.ViewModels
{
    public partial class MainWindowViewModel :ObservableObject
    {


        [ObservableProperty]//单纯的展示页面跳转使用IEnumerable或list即可，增删改需要用Collection
        IEnumerable<Employee> employeeDisplay; //绑定到前台

        [ObservableProperty]
        private int pageMaxCount;

        [ObservableProperty]
        private int pageIndex;

        partial void OnPageIndexChanged(int value)
        {
            GoTo(value);
        }

        private int pageNumber;

        private IFreeSql fsql;

        private const int PageSize = 15;//const常量
        public MainWindowViewModel()
        {
            fsql = new FreeSqlBuilder()
                .UseConnectionString(DataType.Sqlite, "Data Source=demo.db")
                .Build();
            PageMaxCount = (int)Math.Ceiling((double)fsql.Select<Employee>().Count()/PageSize);
            //Math.Ceiling的作用：向上取整，保证190后的数据也能展示
            EmployeeDisplay = fsql.Select<Employee>().Page(1,PageSize).ToList();
        }

        [RelayCommand]
        void GoTo(string pageNumber) 
        {
            GoTo(int.Parse(pageNumber));   
        }

        void GoTo(int pageNumber) 
        {
            EmployeeDisplay = fsql.Select<Employee>().Page(pageNumber, PageSize).ToList();

        }
    }
}
